package com.ruoyi.ghxx.service.impl;

import java.io.File;
import java.util.List;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ghxx.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ghxx.mapper.SysUploadMapper;
import com.ruoyi.ghxx.domain.SysUpload;
import com.ruoyi.ghxx.service.ISysUploadService;

/**
 * 上传信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-11-17
 */
@Service
public class SysUploadServiceImpl implements ISysUploadService 
{
    @Autowired
    private SysUploadMapper sysUploadMapper;

    /**
     * 查询上传信息
     * 
     * @param id 上传信息ID
     * @return 上传信息
     */
    @Override
    public SysUpload selectSysUploadById(Long id)
    {
        return sysUploadMapper.selectSysUploadById(id);
    }

    /**
     * 查询上传信息列表
     * 
     * @param sysUpload 上传信息
     * @return 上传信息
     */
    @Override
    public List<SysUpload> selectSysUploadList(SysUpload sysUpload)
    {
        return sysUploadMapper.selectSysUploadList(sysUpload);
    }

    /**
     * 新增上传信息
     * 
     * @param sysUpload 上传信息
     * @return 结果
     */
    @Override
    public int insertSysUpload(SysUpload sysUpload)
    {
        //生成19位的唯一id
        Snowflake snowflake = IdUtil.getSnowflake(6, 2);
        long id = snowflake.nextId();
        sysUpload.setId(id);
        return sysUploadMapper.insertSysUpload(sysUpload);
    }

    /**
     * 修改上传信息
     * 
     * @param sysUpload 上传信息
     * @return 结果
     */
    @Override
    public int updateSysUpload(SysUpload sysUpload)
    {
        sysUpload.setUpdateTime(DateUtils.getNowDate());
        return sysUploadMapper.updateSysUpload(sysUpload);
    }

    /**
     * 批量删除上传信息
     * 
     * @param ids 需要删除的上传信息ID
     * @return 结果
     */
    @Override
    public int deleteSysUploadByIds(Long[] ids)
    {
        for (int i=0;i<ids.length;i++){
            Long id=ids[i];
            SysUpload sysUpload = sysUploadMapper.selectSysUploadById(id);
            if(Detect.notEmpty(sysUpload.getResourceUrl())){
                String newUrl = sysUpload.getResourceUrl().replace("/profile", "").replace("/avatar", "");
                File file=new File(RuoYiConfig.getAvatarPath()+newUrl);
                if(file.exists()){
                    System.out.println("删除成功");
                    file.delete();
                }
            }
        }
        sysUploadMapper.deleteSysUploadByIds(ids);
        return 1;
    }

    /**
     * 删除上传信息信息
     * 
     * @param id 上传信息ID
     * @return 结果
     */
    @Override
    public int deleteSysUploadById(Long id)
    {
        return sysUploadMapper.deleteSysUploadById(id);
    }
}
